package com.demarc.pesquisas.web.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang3.StringUtils;

import com.demarc.pesquisas.infraestrutura.mensagem.MensagemJsfUtils;
import com.demarc.pesquisas.infraestrutura.web.jsf.JsfUtil;

@FacesConverter(value = "NumeroConverter")
public class NumeroConverter implements Converter {

	private static final String NUMERO_COVNERTER_MESSAGE_ID = "com.demarc.pesquisas.web.converter.NumeroConverter.NUMERO";

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {

		Object retorno = null;
		if (StringUtils.isNotBlank(value)) {
			if (StringUtils.isNumeric(value)) {
				try {
					retorno = Integer.parseInt(value.trim());
				} catch (NumberFormatException e) {
					retorno = Long.parseLong(value.trim());
				}
			} else {
				throw new ConverterException(
						getErrorMessage(context, component));
			}
		}
		return retorno;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object input) {

		String value = StringUtils.EMPTY;
		if (input != null) {
			value = input.toString();
		}
		return value;
	}

	protected FacesMessage getErrorMessage(FacesContext context,
			UIComponent component) {
		return MensagemJsfUtils.criarFacesMessage(FacesMessage.SEVERITY_ERROR,
				NUMERO_COVNERTER_MESSAGE_ID,
				JsfUtil.getLabel(context, component));
	}
}